//
//  TabMineHistoryDeposit.swift
//  kz
//
//  Created by Tech_001 on 22/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import MJRefresh

struct HistoryType {
    public static let deposit = "存款历史"
    public static let withdraw = "取款历史"
    public static let transfer = "转账记录"
    public static let message = "历史消息"
    
    public static let order = "投注记录查询"
    public static let bonus = "红利返水查询"
}

extension String {
    func convertHtmlSymbols() throws -> String? {
        guard let data = data(using: .utf8) else { return nil }
        return try NSAttributedString(data: data, options:[NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:String.Encoding.utf8.rawValue] , documentAttributes: nil).string
      //  return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil).string
    }
}

class TabMineHistoryDepositController: UITableViewController {    
    var requestPath: String?
    var requestType: String?
    
    var offset = 0
    var pageCount = 50
    var loadingData = false
    var noMoreData = false
    
    var rowHeight: CGFloat?
    var data: [[String:Any]]? = [[:]]
    var refreshPage: Int {
        return data!.count
    }
    
    var _loadView: UIView?
    
    var selectedMessage: [UIView:[String:String]]? = [:]
    
    let bottomLabelText: [String:[String]] = [
        HistoryType.deposit: [
            "申请金额",
            "实际金额",
            "单号"
        ],
        HistoryType.withdraw: [
            "申请金额",
            "手续费",
            "单号"
        ],
        HistoryType.transfer: [
            "金额:",
            "",
            "单号"
        ]
    ]
    let bottomLabelColumn: [String:[String]] = [
        HistoryType.deposit: [
            "transtype",
            "status",
            "amount",
            "actual",
            "dno"
        ],
        HistoryType.withdraw: [
            "actual",
            "status",
            "amount",
            "wfee",
            "dno"
        ],
        HistoryType.transfer: [
            "remark",
            "finalresult",
            "",
            "transamount",
            "dno"
        ]
    ]
    
    let rc: MJRefreshHeader? = MJRefreshNormalHeader()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.backBarButtonItem?.title = " "
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        let topLogo = UIImage(named: "top_icon")
//        let ratio = topLogo!.size.height/topLogo!.size.width
//        let newWidth = UIHelper.fullSize.width * 0.4
//        let newHeight = newWidth * ratio
//        
//        let titleView = UIView()
//        let topLogoView = UIImageView(image: topLogo)
//        
//        titleView.addSubview(topLogoView)
//        topLogoView.contentMode = .scaleToFill
//        topLogoView.frame = CGRect(x: -(newWidth/2), y: -(newHeight/2), width: newWidth, height: newHeight)
//        
//        self.navigationItem.titleView = titleView
        self.rowHeight = tableView.rowHeight
        self.data?.removeAll()
        self.selectedMessage?.removeAll()
        
        rc!.setRefreshingTarget(self, refreshingAction: #selector(self.pullToRefresh))
        self.tableView.mj_header = rc
        self.tableView.setNeedsLayout()
        self.tableView.layoutIfNeeded()
        
        self.navigationItem.title = self.requestType
        
        let rightItem = UIBarButtonItem(title: "查询", style: .plain, target: self, action: #selector(self.pullToRefreshBtn(gesture:)))
        self.navigationItem.rightBarButtonItem = rightItem
        self.navigationItem.title = self.requestType
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data!.count + 1
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == data!.count {
            if noMoreData == false {
                return CGFloat(44)
            }
            return 44.0 //
        }
        
        if self.requestType != HistoryType.message {
            return self.rowHeight!
        }
        return 96.0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == self.data!.count {
            //Add loading view at the bottom
            let cell = tableView.dequeueReusableCell(withIdentifier: "loadingView", for: indexPath) as! TabMineHistoryNoDataTableCellView
            cell.indicator.startAnimating()
            
            //Hide loading view if no more data available
            if noMoreData {
                cell.noDataLabel.isHidden = false
            }else{
                cell.noDataLabel.isHidden = true
            }
            
            return cell
        }else{
            //Normal listing data
            let data = self.data![indexPath.row]
            
            if self.requestType == HistoryType.message {
                let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! TabMineHistoryMessageTableViewCell
                
                cell.titleLabel.text = data["title"] as? String
                cell.contentLabel.text = data["content"] as? String
                
                
                let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.displayMessage(tapGestureRecognizer:)))
                cell.contentView.isUserInteractionEnabled = true
                cell.contentView.addGestureRecognizer(tapGestureRecognizer)
                
                let message = [
                    "title": "消息正文",
                    "content": data["content"] as! String,
                    "type":HistoryType.message
                ]
                self.selectedMessage?[cell.contentView] = message
                
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "depositCell", for: indexPath) as! TabMineHistoryDepositTableViewCell
                
                cell.topCenterLabel.text = data["created"] as? String
                cell.bottom1LeftLabel.text = bottomLabelText[requestType!]![0]
                cell.bottom2LeftLabel.text = bottomLabelText[requestType!]![1]
                cell.middleLeftLabel.text = "\(bottomLabelText[requestType!]![2]): \(data[bottomLabelColumn[requestType!]![4]] as! String)"
                
                cell.topLeftLabel.text = data[bottomLabelColumn[requestType!]![0]] as? String
                cell.topRightLabel.text = data[bottomLabelColumn[requestType!]![1]] as? String
                cell.bottom1RightLabel.text = data[bottomLabelColumn[requestType!]![2]] as? String
                cell.bottom2RightLabel.text = data[bottomLabelColumn[requestType!]![3]] as? String
                
                if self.requestType == HistoryType.transfer {
                    if let superView = cell.bottom1LeftLabel.superview {
                        cell.bottomLeftWidthConstraint.constant = 0
                        cell.bottomRightWidthConstraint.constant = 0
                        
                        cell.bottom2RightLabel.textColor = UIColor.init(red: 0, green: 0.7, blue: 0, alpha: 1)
                        
                        let content = "\(cell.middleLeftLabel.text!)\n金额：\(cell.bottom2RightLabel.text!)\n时间：\(data["created"] as! String)"
                       cell.bottom2RightLabel.text = "+" + cell.bottom2RightLabel.text!
          

                        
                        do{
                            cell.topLeftLabel.text = try cell.topLeftLabel.text?.convertHtmlSymbols()

                        } catch {
                            
                        }
                        
                        //Message
                        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.displayMessage(tapGestureRecognizer:)))
                        cell.contentView.isUserInteractionEnabled = true
                        cell.contentView.addGestureRecognizer(tapGestureRecognizer)
                 
                        
                        let message = [
                            "dno": (data[bottomLabelColumn[requestType!]![4]] as! String),
                            "title": cell.topLeftLabel.text!,
                            "content": content,
                            "amount": cell.bottom2RightLabel.text!,
                            "time":data["created"] as! String,
                            "type":HistoryType.transfer
                        ]
                        self.selectedMessage?[cell.contentView] = message
                    }
                }else if self.requestType == HistoryType.deposit {
                    //Message
                    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.displayMessage(tapGestureRecognizer:)))
                    cell.contentView.isUserInteractionEnabled = true
                    cell.contentView.addGestureRecognizer(tapGestureRecognizer)
                    
                    let content = "\(cell.middleLeftLabel.text!)\n申请金额：\(cell.bottom1RightLabel.text!)\n实际金额：\(cell.bottom2RightLabel.text!)\n时间：\(data["created"] as! String)\n状态：\(cell.topRightLabel.text!)"
                    
                    let message = [
                        "dno": (data[bottomLabelColumn[requestType!]![4]] as! String),
                        "title": cell.topLeftLabel.text!,
                        "content": content,
                        "amount": cell.bottom1RightLabel.text!,
                        "amount2": cell.bottom2RightLabel.text!,
                        "time":data["created"] as! String,
                        "status":cell.topRightLabel.text!,
                        "type":HistoryType.deposit
                    ]
                    self.selectedMessage?[cell.contentView] = message
                }else if self.requestType==HistoryType.withdraw{
                    //Message
                    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.displayMessage(tapGestureRecognizer:)))
                    cell.contentView.isUserInteractionEnabled = true
                    cell.contentView.addGestureRecognizer(tapGestureRecognizer)
                    
                    let content = "\(cell.middleLeftLabel.text!)\n申请金额：\(cell.bottom1RightLabel.text!)\n实际金额：\(cell.bottom2RightLabel.text!)\n时间：\(data["created"] as! String)\n状态：\(cell.topRightLabel.text!)"
                    
                    let message = [
                        "dno": (data[bottomLabelColumn[requestType!]![4]] as! String),
                        "title": cell.topLeftLabel.text!,
                        "content": content,
                        "amount": cell.bottom1RightLabel.text!,
                        "amount2": cell.bottom2RightLabel.text!,
                        "time":data["created"] as! String,
                        "status":cell.topRightLabel.text!,
                        "type":HistoryType.withdraw
                    ]
                    self.selectedMessage?[cell.contentView] = message
                    
                }
                
                //Add seperator line
                if UIHelper.fullSize.height >= ScreenSize.iPhone6.height {
                    let y = cell.frame.height/3 + 2
                    let view = UIView()
                    view.frame = CGRect(x: UIHelper.fullSize.width/2 - 0.5, y: y, width: 1, height: 42.67)
                    view.backgroundColor = UIColor.groupTableViewBackground
                    
                    cell.contentView.addSubview(view)
                }

                //self.checkStatus(cell.topRightLabel)
                
                return cell
            }
        }
        
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
     
        if !loadingData && !noMoreData && indexPath.row == data!.count {
            loadingData = true
            pullToRefresh(loadMore: true)
        }
    }
    
    
    @objc func displayMessage(tapGestureRecognizer: UITapGestureRecognizer){
        if let view = tapGestureRecognizer.view {
            if let message = self.selectedMessage?[view] {
                let msg = message["type"]
                
                if msg == HistoryType.message{ //站内信
                    PopWindowHelper.showMsgPopView(title: message["title"]! as NSString, subTitle: message["content"]! as NSString)
                }else if msg == HistoryType.deposit||msg == HistoryType.withdraw{ //存款,取款历史
                    PopWindowHelper.showAmountRecordPopView(title: message["title"]! as NSString, msg: message)
                }else if msg == HistoryType.transfer{ //转帐记录
                    PopWindowHelper.showTransferRecordPopView(title:  message["title"]! as NSString, msg: message)
                }
               
              //  UIHelper.alertSimpleMessagemt(about: message["title"]!, withDescription: message["content"]!, in: self, withOKButton: true)
            }
        }
    }
    
    @objc func pullToRefreshBtn(gesture: UIGestureRecognizer){
        self._loadView?.removeFromSuperview()
        self._loadView = UIHelper.initLoadView(self, withMessage: "获取中...")
        self.tabBarController?.view.addSubview(self._loadView!)
        self.tableView.setContentOffset(CGPoint(x: 0, y: -64), animated: false)
        
        self.pullToRefresh()
    }
    
    @objc func pullToRefresh(loadMore: Bool = false){
        if loadMore == false {
            self.offset = 0
            noMoreData = false
            loadingData = true
        }
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        let calendar = Calendar.current
        let startDate = calendar.date(byAdding: .day, value: -14, to: Date())
        let endDate = calendar.date(byAdding: .day, value: 0, to: Date())
        let startDateString = dateFormatter.string(from: startDate!)
        let endDateString = dateFormatter.string(from: endDate!)
        
        let params =  [
            "offset": String(self.offset),
            "pageCount": String(self.pageCount),
            "start": startDateString + " 00:00:00",
            "end": endDateString + " 23:59:59",
        ]
        print(params)
        
        RequestHelper.post(atPath: self.requestPath!, withData: params, withCompletion: { data in
            do{
                let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
                print("数据\(dataArray)")
                let numToAdd = dataArray.count
                DispatchQueue.main.async {
                    if numToAdd > 0 {
                        if (loadMore == false) {
                            self.data!.removeAll()
                            self.selectedMessage!.removeAll()
                        }
                        for entry in dataArray {
                            self.data!.append(entry)
                        }
                        
                        self.offset += numToAdd
                        self.tableView.reloadData()
                    }else{
                    
                        self.noMoreData = true
                        self.tableView.reloadData()
                    }
                    if(self.requestType == HistoryType.message){
                        self.noMoreData=true
                    }
                    
                    self.loadingData = false
                    self._loadView?.removeFromSuperview()
                    self.rc?.endRefreshing()
                }
            } catch {
                print(String(data: data, encoding: .utf8))
                DispatchQueue.main.async {
                    self._loadView?.removeFromSuperview()
                    self.rc?.endRefreshing()
                    UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生错误", in: self)
                }
            }
        
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                self._loadView?.removeFromSuperview()
                self.rc?.endRefreshing()
                UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生错误\(getErrorString())", in: self)
            }
        })
    }
    
    func checkStatus(_ label: UILabel){
        if label.text!.contains("成功") == true {
            label.textColor = UIColor.init(red: 0, green: 0.7, blue: 0, alpha: 1)
        }else if label.text!.contains("拒绝") == true {
            label.textColor = UIColor.init(red: 0.7, green: 0, blue: 0, alpha: 1)
        }
    }
}
